package models

import (
	"errors"
	"fmt"
	"gitee.com/lzqysoft/ims/libs"
	"gitee.com/lzqysoft/ims/libs/params"
	"reflect"
	"strings"
	"time"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

type Menu struct {
	Id           string        `orm:"column(id);pk"`
	Pid          string        `orm:"column(pid)"`
	Name         string        `orm:"column(name)"`
	Folder       string        `orm:"column(folder)"`
	Remark       string        `orm:"column(remark)"`
	Icon         string        `orm:"column(icon);null"`
	Type         int           `orm:"column(type)"`
	Articles     []*Article    `orm:"reverse(many)"`
	Organization *Organization `orm:"rel(fk);column(org_id)"`
	Status       int           `orm:"column(status)"`
	IsDelete     int           `orm:"column(isdelete)"`
	Ctime        time.Time     `orm:"column(ctime);type(timestamp without time zone)"`
	Creater      string        `orm:"column(creater)"`
	Utime        time.Time     `orm:"column(utime);type(timestamp without time zone)"`
	Updater      string        `orm:"column(updater)"`
	Seq          int           `orm:"column(seq)"`
	OrgName      string        `orm:"column(org_name)"`
}

func (t *Menu) TableName() string {
	return "cms_menu"
}

func init() {
	orm.RegisterModel(new(Menu))
}

func AddMenu(m *Menu, org *Organization) (err error) {
	path := beego.AppConfig.String("WebRootDir") + "/" + org.Context + "/" + "content"
	stdout, err := libs.Mkdir(m.Folder, path)
	// TODO create _index.md
	if err != nil {
		beego.Debug(string(stdout))
		return
	}
	o := orm.NewOrm()
	_, err = o.Insert(m)
	return
}

func SoftDeleteMenu(id, uname string) (err error) {
	o := orm.NewOrm()

	//	err = o.Begin() // 事务处理过程

	v := Menu{Id: id}
	if err = o.Read(&v); err == nil {
		v.IsDelete = 1
		v.Updater = uname
		v.Utime = time.Now()
		_, err = o.Update(&v)
	}
	return
}

func UpdateMenu(m *Menu) (err error) {
	o := orm.NewOrm()
	v := Menu{Id: m.Id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Update(m); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}

func GetMenuById(id string) (v *Menu, err error) {
	o := orm.NewOrm()
	v = &Menu{Id: id}
	if err = o.Read(v); err == nil {
		o.LoadRelated(v, "Organization")
		return v, nil
	}
	return nil, err
}

func GetAllMenus(query map[string]string, fields []string, sortby []string, order []string,
	offset int64, limit int64) (ml []interface{}, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Menu))
	// query k=v
	for k, v := range query {
		// rewrite dot-notation to Object__Attribute
		k = strings.Replace(k, ".", "__", -1)
		qs = qs.Filter(k, v)
	}
	qs = qs.Filter("IsDelete", 0)
	// order by:
	var sortFields []string
	if len(sortby) != 0 {
		if len(sortby) == len(order) {
			// 1) for each sort field, there is an associated order
			for i, v := range sortby {
				orderby := ""
				if order[i] == "desc" {
					orderby = "-" + v
				} else if order[i] == "asc" {
					orderby = v
				} else {
					return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
			qs = qs.OrderBy(sortFields...)
		} else if len(sortby) != len(order) && len(order) == 1 {
			// 2) there is exactly one order, all the sorted fields will be sorted by this order
			for _, v := range sortby {
				orderby := ""
				if order[0] == "desc" {
					orderby = "-" + v
				} else if order[0] == "asc" {
					orderby = v
				} else {
					return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
		} else if len(sortby) != len(order) && len(order) != 1 {
			return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
		}
	} else {
		if len(order) != 0 {
			return nil, errors.New("Error: unused 'order' fields")
		}
	}

	var l []orm.Params
	qs = qs.RelatedSel().OrderBy(sortFields...)
	if _, err = qs.Limit(limit, offset).Values(&l, fields...); err == nil {
		if len(fields) == 0 {
			for _, v := range l {
				u, _ := GetMenuById(v["Id"].(string))
				r, err := GetMenuById(v["Pid"].(string))
				if err == nil && len(r.Name) > 0 {
					v["Pname"] = r.Name
				} else {
					v["Pname"] = "顶级栏目"
				}
				v["OrgId"] = u.Organization.Id
				v["OrgName"] = u.Organization.Name
				v["Sname"] = params.GetStatus(u.Status)
				ml = append(ml, v)
			}
		} else {
			// trim unused fields
			for _, v := range l {
				m := make(map[string]interface{})
				val := reflect.ValueOf(v)
				for _, fname := range fields {
					m[fname] = val.FieldByName(fname).Interface()
				}
				ml = append(ml, m)
			}
		}
		return ml, nil
	}
	return nil, err
}

func GetMenusTree(user *User) (nodes []map[string]interface{}, err error) {
	var lists []*Menu
	o := orm.NewOrm()
	qs := o.QueryTable(new(Menu)).Filter("org_id", user.Organization.Id).Filter("status", 1).Filter("isdelete", 0)
	if _, err = qs.All(&lists); err != nil {
		beego.Debug(err)
		return
	}

	beego.Debug(lists)
	if len(lists) < 1 {
		return
	}
	root := make(map[string]interface{})
	m := &Menu{}
	ks := o.QueryTable(new(Menu)).Filter("org_id", user.Organization.Id).Filter("status", 1).
		Filter("isdelete", 0).Filter("pid", "0")
	if err = ks.One(m); err != nil {
		beego.Debug(err)
		return
	}
	root["title"] = m.Name
	root["id"] = m.Id
	root["expand"] = true
	root["icon"] = "md-school"
	root["children"] = make([]map[string]interface{}, 0)
	getMenuTree(lists, m.Id, root)
	nodes = append(nodes, root)
	return nodes, nil
}

func getMenuTree(menus []*Menu, pid string, node map[string]interface{}) {

	for _, v := range menus {
		if v.Pid == pid {
			n := make(map[string]interface{})
			n["title"] = v.Name
			n["id"] = v.Id
			n["expand"] = true
			n["children"] = make([]map[string]interface{}, 0)
			getMenuTree(menus, v.Id, n)
			node["children"] = append(node["children"].([]map[string]interface{}), n)
			//beego.Debug("getMenuTree")
		}
	}
}

func GetMenuByPid(id string) (menus []Menu, err error) {
	o := orm.NewOrm()
	if _, err := o.QueryTable(new(Menu)).Filter("IsDelete", 0).Filter("pid", id).All(&menus); err == nil {
		return menus, nil
	} else {
		return nil, err
	}
}

type MenuTree struct {
	Name     string     `json:"name"`
	Id       string     `json:"id"`
	Logo     string     `json:"logo"`
	Folder   string     `json:"folder"`
	Expand   bool       `json:"expand"`
	Children []MenuTree `json:"children"`
}

// 通过单位id查询Menu
func GetMenuByOrg(orgId string) (tree []MenuTree, err error) {
	var lists []*Menu
	o := orm.NewOrm()
	qs := o.QueryTable(new(Menu)).
		Filter("org_id", orgId).Filter("status", 1).Filter("isdelete", 0).OrderBy("Seq")
	if _, err = qs.All(&lists); err != nil {
		return
	}
	tree = make([]MenuTree, 0)
	for _, m := range lists {
		if m.Pid == "0" {
			node := MenuTree{m.Name, m.Id, "clipboard", m.Folder, true, make([]MenuTree, 0)}
			for _, v := range lists {
				if v.Pid == m.Id {
					n := MenuTree{v.Name, v.Id, "clipboard", m.Folder, true, make([]MenuTree, 0)}
					node.Children = append(node.Children, n)
				}
			}
			tree = append(tree, node)
		}
	}
	return
}
